package com.lyf.springbootdemo01.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Classname:HelloController
 * Package:com.lyf.springbootdemo01.controller
 * Description:
 *
 * @Date:2021/8/10 21:31
 * @Author:lyf.0317
 */
@Controller
public class HelloController {
    //跨域ip
    final String ip = "http://192.168.43.218:8080";
    @Autowired
    JdbcTemplate jdbcTemplate;
    @CrossOrigin(origins = ip)
    @ResponseBody
    @GetMapping("/api/login-check")
    private Map<String,Object> map(@RequestParam("acc") String acc, @RequestParam("pd") String pd){



        String sql  = "select acc, password,id,name from user where acc= '" + acc + "'";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        HashMap<String , Object > map = new HashMap<>();


        if (list.size() == 0){
            map.put("state","failure");
            map.put("problem","acc");
            return map;
        }
        String pd1 = (String) list.get(0).get("password");
        if(pd1.equals(pd)){
            map.put("state","success");
            map.put("id",list.get(0).get("id"));
            map.put("name",list.get(0).get("name"));

        }else {
            map.put("state","failure");
            map.put("problem","pd");
        }
        return map;

    }
    @CrossOrigin(origins =ip)
    @ResponseBody
    @GetMapping("/api/register-check")
    public Map<String,Object>  register (@RequestParam("acc") String acc,@RequestParam("pd") String pd,
                                         @RequestParam("name") String name,
                                         @RequestParam("motto") String motto){
       String sql = "select acc from user where acc=" + acc;
       Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        if (list.size() == 0){

          try{
              String  sql2 = "insert into user( name,acc,password,motto,register_date) " + "values('" + name + "','" + acc + "','" + pd + "','" + motto + "','" +  "2019-09-09"+"')";
            jdbcTemplate.update(sql2);
          }
          catch( Exception e){
          System.out.println("异常");
          map.put("state","failure");
          return map;
          }
          map.put("state","success");
          return  map;
        }
        map.put("state","failure");
        return  map;



    }

    //切片
    public List query(List list,int pageNum){
        List value = null;


        int remainder = list.size()%6;
        int offset = (pageNum - 1 )*6 ;
        System.out.println(pageNum);
        if(list.size() % 6 == 0 ){
            value = list.subList(offset,offset + 6);

        }else if(pageNum < (list.size()/6) + 1  ){
            value = list.subList(offset,offset + 6);
        }else {
            value = list.subList(offset,offset + remainder);
        }


        return value;

    }

    @CrossOrigin(origins =ip)
    @ResponseBody
    @GetMapping("/api/index")
    public Map<String,Object> queryLatestArticle(){
        //查询最新的文章
        String latestArticlesSql = "select article.*,user.name name " +
                "from article,user " +
                "where article.user_id = user.id " +
                "order by created_date desc";
        Map<String,Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> list = jdbcTemplate.queryForList(latestArticlesSql);
        map.put("latestArticles",list);

        //查询最热门的文章

        String hotArticleSql = "select id,title,read_num "+
                "from article "+
                "order by read_num desc "+
                "limit 10";
        List<Map<String, Object>> list1 = jdbcTemplate.queryForList(hotArticleSql);
        map.put("hotArticles",list1);
        //查询当前页码
        if( list.size() != 0){
            map.put("pageNum",1);
            if(list.size()%6 == 0){
                map.put("totalNum",list.size()/6);
            }else {
                map.put("totalNum",(Integer)list.size()/6 + 1);
            }
            System.out.println();
        }else{
            map.put("pageNum",0);
        }

        if(list.size() > 6){
            map.put("latestArticles",list.subList(0,6));
        }
        else{
            map.put("latestArticles",list);
        }


        Calendar calendar = Calendar.getInstance(); // get current instance of the calendar
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy ");
        System.out.println(formatter.format(calendar.getTime()));
        map.put("time",formatter.format(calendar.getTime()));
        return map ;
    }


    //查看文章
    @CrossOrigin(origins =ip)
    @ResponseBody
    @RequestMapping("/api/detail")
    public Map<String,Object> detail(@RequestParam("id") String id){
        // 文章信息articleInfo
        String articleInfoSql = "select * from article where id=" + id;
        // 阅读数量加一
        String readNumIncrSql = "update article set read_num = read_num + 1 where id=" + id;

        Map<String,Object> map = new HashMap<String, Object>();
        int newReadNum  = jdbcTemplate.update(readNumIncrSql);
        List<Map<String, Object>> list  = jdbcTemplate.queryForList(articleInfoSql);
        map.put("read_num",newReadNum);
        map.put("articleInfo",list.get(0));

        int userId = (Integer) list.get(0).get("user_id");
        // 用户信息userInfo
        String userInfoSql = "select * from user where id=" + userId;
        //originalArticleNum
        String originalArticleNumSql = "select count(id) from article where " +
                                        "is_original=1 and user_id= " + userId;
        List<Map<String, Object>> list1  = jdbcTemplate.queryForList(userInfoSql);
        List<Map<String, Object>> list2  = jdbcTemplate.queryForList(originalArticleNumSql);
        Map<String,Object> user =  list1.get(0);
        user.put("originalArticleNum",list2.get(0).get("count(id)"));
        list.get(0).put("author",user.get("name"));
        System.out.println(list.get(0).get("name"));
        System.out.println(user);
        // 所有发表文章的阅读数量readNumTotal
        String readNumTotalSql = "select sum(read_num) from article where user_id = " + userId;
        List<Map<String,Object>> list3 = jdbcTemplate.queryForList(readNumTotalSql);
        user.put("readNumTotal",list3.get(0).get("sum(read_num)"));

        user.remove("accout");
        user.remove("password");

        map.put("authorInfo",user);


        //文章信息 articleInfo
        Map<String,Object> map3 = new HashMap<String, Object>();
        // 作者近期五篇文章latestArticles
        String latestArticlesSql = "select * from article where user_id = "
                                     + userId + " limit 5";
        List<Map<String,Object>> list4 = jdbcTemplate.queryForList(latestArticlesSql);
        System.out.println(list4);
        map.put("latestArticles",list4);


        return map;

    }
    //写文章
    @CrossOrigin(origins =ip)
    @ResponseBody
    @RequestMapping("/api/save-article")
    public  Map<String,Object> write (@RequestParam("userId") String userId,
                                      @RequestParam("title") String title,
                                      @RequestParam("content") String content,
                                      @RequestParam("tag") String tag,
                                      @RequestParam("isOriginal") Integer isOriginal,
                                      @RequestParam("isPublic") Integer isPublic){
        Calendar calender = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String date = formatter.format(calender.getTime());
        String updateDate = date;
        String createdDate = date;
        String  saveArticle = "insert " +
                "into article(title,content,update_date,created_date,tag,is_public,is_original,user_id,read_num) " +
                "values('" + title + "','" + content + "','" + updateDate + "','" + createdDate + "','" + tag + "',"  +
                 isPublic + "," + isOriginal + "," + userId + "," + "0)";
        Map<String,Object> map = new HashMap<String, Object>();
        int list =  jdbcTemplate.update(saveArticle);

        return  map;
    }




    //文章搜索与换页功能
    @CrossOrigin(origins = ip)
    @ResponseBody
    @RequestMapping("/api/change-page")
    public Map<String,Object> changePage(@RequestParam("pageNum") int pageNum,
                                         @RequestParam("keyword") String keyword,
                                         @RequestParam("tag") String tag){
        Map<String,Object> map = new HashMap<String, Object>();
        // 查询某个关键词的文章
        String articlesWidthKeywordSql = "select * from article where tag like '%" + keyword
                + "%' or " + "title like '%" + keyword + "%' or " + "content like '%"
                + keyword + "%'" +" order by read_num desc";

        // 查询某个标签的文章
        String articlesWithTagSql = "select * from article where tag='" + tag
                + "' order by read_num desc";
        // 查询最新文章
        String  latestArticlesSql = "select * from article order by created_date desc";

        List<Map<String,Object>> list;

        if(keyword != ""){
           //获取keyword查询到的文章列表
           list  = jdbcTemplate.queryForList(articlesWidthKeywordSql);
       }else if(tag != ""){
           //获取tag查询到的文章列表
            list  = jdbcTemplate.queryForList(articlesWithTagSql);

       }else{
            //获取最新发表文章列表
            list  = jdbcTemplate.queryForList(latestArticlesSql);

        }

        if(list.size()%6 == 0){
            map.put("totalNum",list.size()/6);
        }else{
            map.put("totalNum",list.size()/6 + 1);
        }
        if(list.size() == 0){
            pageNum = 0;
        }
        map.put("pageNum",pageNum);

        if(pageNum==0){
            map.put("articles", null);
        }
        else{
            map.put("articles",this.query(list,pageNum));
        }
        //获取keyword查询到的文章列表
        //List<Map<String,Object>> list  = jdbcTemplate.queryForList(articlesWidthKeywordSql);
        //获取关键词查询结果
        return map;
    }

    //个人界面
    @CrossOrigin(origins = ip)
    @ResponseBody
    @RequestMapping("/api/profile")
    public Map<String,Object> myInfo(@RequestParam("id") int id){
        Map<String,Object> map = new HashMap<String, Object>() ;
        //根据用户id获取到的用户信息
        String userInfoSql = "select * from user where id =" + id;
        List<Map<String,Object>> list = jdbcTemplate.queryForList(userInfoSql);

        //所有发表文章的总阅读数量
        String totalArticleNumSql = "select article.*,user.name name from article,user where user.id="
                               + id + " and article.user_id=user.id order by created_date";
          List<Map<String,Object>> list1 = jdbcTemplate.queryForList(totalArticleNumSql);
          int originalArticleNum = 0;
          int readNumTotal = 0;
        for(int i = 0;i<list1.size();i++){

                originalArticleNum += (int)list1.get(i).get("is_original");


        }


        for(int i = 0;i<list1.size();i++){

            readNumTotal += (int)list1.get(i).get("read_num");
        }
        list.get(0).put("originalArticleNum",originalArticleNum);
        list.get(0).put("readNumTotal",readNumTotal);
        list.get(0).remove("acc");
        list.get(0).remove("password");

        for(int i = 0 ; i<list1.size(); i++){
            list1.get(i).remove("user_id");
        }
        map.put("authorInfo",list.get(0));


        map.put("articles",list1);
        return  map;
    }




}



